package com.fingard.dsp.bank.directbank.yeepay02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.util.FtpUtil;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.client.YopResponse;
import com.yeepay.g3.sdk.yop.client.YopRsaClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class YEEPAY02Statement extends YEEPAY02Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();
        RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
            if (actItem == null) {
                retAts.writeRespCode("-1");
                if (actItem == null) {
                    retAts.writeRespInfo("未找到账号" + p_reqQrySttm.actNum + "的商户配置节点");
                }
                retAts.writeRetDetail(retDetail);
                return retAts;
            }
            Map<String, String> params = new HashMap<String, String>();
            params.put("appKey", actItem.appKey);
            /** 获取时间戳 */
            Date date = p_reqQrySttm.getBusDate();
            Calendar ts = Calendar.getInstance();
            ts.setTime(date);
            String transTime = String.valueOf(ts.getTimeInMillis());
            params.put("ts", transTime);
            params.put("merchantNo", actItem.merchantId);
            params.put("dayString", Format.Date10Format.format(date));
            params.put("dataType", "success");
            String downFileName = p_reqQrySttm.actNum + p_reqQrySttm.busDate + ".txt";

            String localFilePath = createTempFileDirectory() + File.separator + downFileName;
            String url = bankFront.getUrl("statement");
            WriteBankLogLn("提交银行的地址后缀：" + url);
            YopRequest request = new YopRequest(actItem.merchantId, actItem.ownKeyStorePath);
            request.addParam("parentMerchantNo", actItem.inMerchantId);
            request.addParam("merchantNo", actItem.merchantId);
            request.addParam("dayString", params.get("dayString"));
            request.addParam("dataType", params.get("dataType"));
            YopResponse tmpresponse = YopRsaClient.get(url, request);
            WriteBankLogLn("response:" + tmpresponse.toString());
            if (tmpresponse != null) {
                String status = tmpresponse.getState();
                Map map = parseResponse(tmpresponse.getStringResult());
                if ("SUCCESS".equals(status)) {
                    InputStream returnStream = tmpresponse.getFile();
                    OutputStream outputStream = null;
                    if (returnStream != null) {
                        File file = new File(localFilePath);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        outputStream = new FileOutputStream(file);
                        byte[] bs = new byte[1024];
                        int readNum;
                        while ((readNum = returnStream.read(bs)) != -1) {
                            outputStream.write(bs, 0, readNum);
                        }
                        String fileContent = FtpUtil.getTextFromFile(localFilePath, getCharset());
                        if (fileContent != null) {
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo(map.get("errorMsg").toString());
                            WriteBankLogLn("对账单内容:" + fileContent);
                            String[] totalLine = fileContent.split("\r\n");

                            /**
                             * 对账单文件格式
                             *      0           1          2         3       4      5       6        6         7         8         9         10
                             * “商户批次号”,”商户订单号”,”创建时间”,”银行名称”,”户名”,”账号”,”打款金额”,”手续费”,”实付金额”,”易宝状态”,”银行状态”,”业务类型”
                             */
                            if (totalLine.length > 0) {
                                for (int i = 0; i < totalLine.length; i++) {
                                    String[] eachLine = totalLine[i].split(",");
                                    retDetail.reqBatchNO = eachLine[0];
                                    retDetail.channelOrderNo = eachLine[1];
                                    retDetail.busTime = eachLine[2];
                                    retDetail.oppBank = eachLine[3];
                                    retDetail.oppActName = eachLine[4];
                                    retDetail.oppAct = eachLine[5];
                                    retDetail.amount = eachLine[6];
                                    retDetail.buyerPayAmount = eachLine[7];
                                    retDetail.busType = eachLine[10];
                                    retDetail.transState = TransState.Success;
                                    retAts.writeRetDetail(retDetail);
                                }
                            }
                        } else {
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo("读取对账单失败！");
                        }
                    } else {
                        retAts.writeRespCode("0");
                        retAts.writeRespInfo("交易为空");
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(map.get("errorMsg").toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(tmpresponse.toString());
            }

        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
